package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.constant.Ali;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.annotation.Resource;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@Api(tags = "登录相关接口")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;
    @Resource
    private ISysUserService userService;
    @Autowired
    private ISysMenuService menuService;
    @Resource
    private Ali ali;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private SysPermissionService permissionService;

    @GetMapping("/get/phoneCode")
    public AjaxResult getPhoneCode(@RequestParam("telePhone") String telePhone) {
        log.info("获取验证码：{}", telePhone);
        if (!MobileUtil.checkPhone(telePhone))
            return AjaxResult.error("请输入正确的手机号码");
        if (StringUtils.isNull(userService.selectUserByPhone(telePhone)))
            return AjaxResult.error("该手机号尚未注册，请联系管理员开通账号");
        try {
            String authCode = RandomUtil.randomAuthCode();
            redisCache.setCacheObject("loginAuthCode" + telePhone, authCode, 3, TimeUnit.MINUTES);
            SmsUtils.sendSms(telePhone, authCode, ali.getTemplateCode());
            return AjaxResult.success("短信发送成功");
        } catch (ClientException e) {
            e.printStackTrace();
            return AjaxResult.error("短信发送失败，请稍后重试");
        }
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        if(loginBody.getCode().length()>=6){
            Object cacheObject = redisCache.getCacheObject("loginAuthCode" + loginBody.getUsername());
            if(StringUtils.isNull(cacheObject))
                return AjaxResult.error("验证码失效，请重新获取");
            if(!loginBody.getCode().equals((String) cacheObject))
                return AjaxResult.error("验证码错误");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation("登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "账号", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String")
    })
    @PostMapping("/appLogin")
    public AjaxResult appLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        //生成令牌
        String token = loginService.appLogin(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
